package com.patrol.auth.controller;

import com.patrol.auth.service.AdminUserService;
import com.patrol.auth.service.EmailCodeService;
import com.patrol.utils.RegexUtil;
import com.patrol.utils.Result;
import io.netty.util.internal.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author 房梦豪
 * @version 1.0
 * @description: TODO
 * @date 2021/9/5 10:11
 */
@Api(value = "邮箱验证码")
@RequestMapping("/api/email")
@RestController
@CrossOrigin
public class EmailCodeController {

    @Resource
    private EmailCodeService emailCodeService;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private AdminUserService adminUserService;

    @ApiOperation(value = "发送验证码")
    @GetMapping("/sendEmailCode/{username}/{email}")
    public Result sendEmailCode(@PathVariable("username") String username,
                                @PathVariable("email") String receiverEmail) {
        if (StringUtil.isNullOrEmpty(username) || StringUtil.isNullOrEmpty(receiverEmail)) {
            return Result.fail("用户名或者邮箱不能为空！");
        }

        if (!RegexUtil.isLetterDigit(username)) {
            return Result.fail("用户名格式不正确");
        }

        if (!RegexUtil.checkEmail(receiverEmail)) {
            return Result.fail("邮箱格式有误！");
        }
        boolean b = emailCodeService.sendEmailCode(receiverEmail, username);
        return b ? Result.ok("发送成功") : Result.fail("邮箱或用户名不存在");
    }

    @ApiOperation(value = "验证码匹配")
    @GetMapping("/matchCode/{code}/{receiver}")
    public Result matchCode(@PathVariable("code") String code,
                            @PathVariable("receiver") String receiver) {
        String emailCode = (String) redisTemplate.opsForValue().get(receiver);
        if (null == code || null == emailCode) {
            return Result.fail("邮箱验证码为空！");
        }
        return code.equals(emailCode) ? Result.ok() : Result.fail("验证码错误");
    }

    @ApiOperation(value = "根据邮箱修改用户密码")
    @GetMapping("/updatePwd/{email}/{pwd}")
    public Result updatePwdByEmail(@PathVariable("email") String email,
                            @PathVariable("pwd") String pwd) {
        if (!RegexUtil.checkEmail(email)) {
            return Result.fail("邮箱格式输入有误！");
        }

        if (StringUtil.isNullOrEmpty(email) || StringUtil.isNullOrEmpty(pwd)) {
            return Result.fail("邮箱或密码不能为空！");
        }

        boolean b = adminUserService.updatePwdByEmail(email, pwd);
        return b ? Result.ok("密码修改成功") : Result.fail("密码修改失败");
    }
}
